// map.js
import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'

//起点标点
var markersLng1 = 'markers[0].longitude';
var markersLat1 = 'markers[0].latitude';

//终点标点
var markersLng2 = 'markers[1].longitude';
var markersLat2 = 'markers[1].latitude';

//连线起点经纬度
var pointsLng1 = 'polyline[0].points[0].longitude';
var pointsLat1 = 'polyline[0].points[0].latitude';

//连线终点经纬度
var pointsLng2 = 'polyline[0].points[1].longitude';
var pointsLat2 = 'polyline[0].points[1].latitude';

//设置视野缩放始终包含两个连线的点
var includeLng1 = 'includePoints[0].longitude';
var includeLat1 = 'includePoints[0].latitude';
var includeLng2 = 'includePoints[1].longitude';
var includeLat2 = 'includePoints[1].latitude';

//起点地址
var startAdress = "markers[0].label.content";

Page({
  data: {
    historyList:"",
    endAddress:"", //存放终点地址
    longitude: 113.324520,
    latitude: 23.099994,
    maskFlag: false,
    maskContent: true,
    enableSatellite: true,//是否显示卫星图
    enable3D: false,//是否显示3D地图
    scale: 12,//放大缩小
    includePoints:[
      {
        longitude: 113.3245211,
        latitude: 23.10229
      }, 
      {
        longitude: 113.324520,
        latitude: 23.08229
      }
    ],
    markers: [
      {
        iconPath: "./img/fangwei.png",
        id: 1,
        longitude: 113.324520,
        latitude: 23.10229,
        width: 400,
        height: 400,
        anchor:{
          x: .5,
          y: .5
        },
        label:{
          content: '',
          color: '#000',
          fontSize: 12,
          borderWidth: 2,
          borderColor: "#9dec6d",
          borderRadius: 2,
          bgColor: "#9dec6d",
          textAlign: "center",
          anchorX: 0,
          anchorY: 0,
          padding: 2,
        },
      },
      {
        id: 2,
        longitude: 113.324520,
        latitude: 23.08229,
        alpha:0.8,
        label:{
          content: '',
          color: '#000',
          fontSize: 12,
          borderWidth: 2,
          borderColor: "#9dec6d",
          borderRadius: 2,
          bgColor: "#9dec6d",
          textAlign: "center",
          padding: 2,
        },
        callout:{
          content: '',
          color: '#000',
          fontSize: 24,
          borderWidth: 2,
          borderColor: "#FF0000DD",
          borderRadius: 6,
          bgColor: "#fff",
          textAlign: "center",
          padding: 4,
          display: "ALWAYS",
        }
      },
    ],
    polyline: [{
      points: [
        {
          longitude: 113.3245211,
          latitude: 23.10229
        }, 
        {
          longitude: 113.324520,
          latitude: 23.08229
        }
      ],
      color:"#FF0000DD",
      width: 2,
      dottedLine: true,
      arrowLine: true,
    }],
  },
  onLoad(){
    var This = this;
    this.getStorage();
    wx.getLocation({
      success (res) {
        //始点经纬度
        var startLongitude = res.longitude;
        var startLatitude = res.latitude;
        //终点经纬度
        var endLongitude = This.data.polyline[0].points[1].longitude;
        var endLatitude = This.data.polyline[0].points[1].latitude;
        //获得起点中文地址
        This.sdkPosition(startLongitude,startLatitude,"start");
        //获得终点中文地址
        This.sdkPosition(endLongitude,endLatitude,"end");
        This.calculateShichen(startLongitude, startLatitude, endLongitude, endLatitude);
        This.setData({
          [markersLng1]:startLongitude,
          [markersLat1]:startLatitude,
          [pointsLng1]:startLongitude,
          [pointsLat1]:startLatitude,
          [includeLng1]: startLongitude,
          [includeLat1]: startLatitude,
          [includeLng2]: endLongitude,
          [includeLat2]: endLatitude,
        })
      }
    })
  },
  //地图定位
  position(){
    var This = this
    wx.getLocation({
      success: function (res) {
        //始点经纬度
        var startLongitude = res.longitude;
        var startLatitude = res.latitude;
        //获得起点中文地址
        This.sdkPosition(startLongitude,startLatitude,"start");
        //终点经纬度
        var endLongitude = This.data.polyline[0].points[1].longitude;
        var endLatitude = This.data.polyline[0].points[1].latitude;
        This.setData({
          longitude: startLongitude,
          latitude: startLatitude,
          [markersLng1]: startLongitude,
          [markersLat1]:startLatitude,
          [pointsLng1]: startLongitude,
          [pointsLat1]:startLatitude,
          [includeLng1]: startLongitude,
          [includeLat1]:startLatitude,
          [includeLng2]: endLongitude,
          [includeLat2]: endLatitude,
        })
        var ELng = This.data.markers[1].longitude;
        var ELat = This.data.markers[1].latitude;
        This.calculateShichen(res.longitude, res.latitude, ELng, ELat);
        This.getDistance();
      },
    })
  },
  // SDK经纬度获取中文地址
  sdkPosition(longitude,latitude,type=''){
    var qqmapsdk = new QQMapWX({
      key: 'DTYBZ-MNUCV-HQOP3-UD5FF-BLBQT-ATFI2' // 必填
    })
    var This = this;
    //起点地址
    var startAdress = "markers[0].label.content";
    // 坐标转换
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        if(type == 'start'){
          This.setData({
            [startAdress]: res.result.address
          })
        }else if(type == 'end'){
          This.setData({
            endAddress: res.result.address,
          })
        }
        This.getDistance();//获取距离
      },
      fail: function (error) {
        console.error('错误', error)
      }
    })
  },
  //起点选择
  qidianSelect(){
    var This = this;
    wx.chooseLocation({
      success:function(res){
        let content = res.name + ":" + res.address;
        This.setStoryage(content);
        var ELng = This.data.markers[1].longitude;
        var ELat = This.data.markers[1].latitude;
        This.calculateShichen(res.longitude, res.latitude, ELng, ELat);
        This.setData({
          [markersLng1]: res.longitude,
          [markersLat1]: res.latitude,
          [pointsLng1]: res.longitude,
          [pointsLat1]: res.latitude,
          [startAdress]: res.address,
          [includeLng1]: res.longitude,
          [includeLat1]: res.latitude,
        })
        This.getDistance();
      }
    })
  },
  //终点选择
  zhongdianSelect(){
    var This = this;
    wx.chooseLocation({
      success:function(res){
        let content = res.name + ":" + res.address;
        This.setStoryage(content);
        var SLng = This.data.markers[0].longitude;
        var SLat = This.data.markers[0].latitude;
        This.calculateShichen(SLng, SLat, res.longitude, res.latitude);
        This.setData({
          [markersLng2]: res.longitude,
          [markersLat2]: res.latitude,
          [pointsLng2]: res.longitude,
          [pointsLat2]: res.latitude,
          [includeLng2]: res.longitude,
          [includeLat2]: res.latitude,
          endAddress:  res.address, //终点地址
        })
        This.getDistance();
      }
    })
  },
  //进行经纬度转换为距离的计算
  getDistance(){
    //始点经纬度
    var startLongitude = this.data.polyline[0].points[0].longitude;
    var startLatitude = this.data.polyline[0].points[0].latitude;
    //终点经纬度
    var endLongitude = this.data.polyline[0].points[1].longitude;
    var endLatitude = this.data.polyline[0].points[1].latitude;
    var lat1 = startLatitude || 0;
    var lng1 = startLongitude || 0;
    var lat2 = endLatitude || 0;
    var lng2 = endLongitude || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
    var s = (distance/1000).toFixed(1) + 'km' + '  ';
    var newAddress = s + this.data.endAddress;
    var markersContent = 'markers[1].label.content';
    this.setData({
      [markersContent]: newAddress
    })
  },
  rad(d){
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
  },
  //计算方位终点时辰方位
  calculateShichen(startLng, startLat, endLng, endLat){
    //转换为整数
    var SLng = startLng * 100000;
    var SLat = startLat * 100000;
    var ELng = endLng * 100000;
    var ELat = endLat * 100000;
    //计算差值
    var LngDiff = ELng - SLng;
    var LatDiff = ELat - SLat;
    //计算差值的绝对值
    var absLngDiff = Math.abs(LngDiff)
    var absLatDiff = Math.abs(LatDiff)
    //保存方位度数
    var angle = 0;

    var textStr = 'markers[1].callout.content';

    if(LngDiff>0 && LatDiff>0){ //第一象限
      //求出弧度
      let radina = Math.atan(absLngDiff/absLatDiff);
      angle = Number((180/(Math.PI/radina)).toFixed(1)) 
    }else if(LngDiff>0 && LatDiff<0){ //第四象限
      //求出弧度
      let radina = Math.atan(absLatDiff/absLngDiff); 
      angle = Number((180/(Math.PI/radina)).toFixed(1)) + 90; 
    }else if(LngDiff<0 && LatDiff<0){ //第三象限
      //求出弧度
      let radina = Math.atan(absLngDiff/absLatDiff);
      angle = Number((180/(Math.PI/radina)).toFixed(1)) + 180;
    }else if(LngDiff<0 && LatDiff>0){ //第二象限
      //求出弧度
      let radina = Math.atan(absLatDiff/absLngDiff);
      angle = Number((180/(Math.PI/radina)).toFixed(1)) + 270;
    }else if(LngDiff==0 && LatDiff>0){ //X轴正数半段
      this.setData({
        [textStr]:'子'
      })
      return
    }else if(LngDiff==0 && LatDiff<0){ //X轴负数半段
      this.setData({
        [textStr]:'午'
      })
      return
    }else if(LngDiff>0 && LatDiff==0){ //Y轴正数半段
      this.setData({
        [textStr]:'卯'
      })
      return
    }else if(LngDiff<0 && LatDiff==0){ //Y轴负数半段
      this.setData({
        [textStr]:'酉'
      })
      return
    }
    this.calculateAngle(angle);
  },
  //根据度数输出方位时辰
  calculateAngle(angle){
    var text = '';
    if(angle >= 352.5 || angle < 7.5){
      text = '子';
    }else if(angle >= 7.5 && angle < 22.5){
      text = '癸';
    }else if(angle >= 22.5 && angle < 37.5){
      text = '丑';
    }else if(angle >= 37.5 && angle < 52.5){
      text = '艮';
    }else if(angle >= 52.5 && angle < 67.5){
      text = '寅';
    }else if(angle >= 67.5 && angle < 82.5){
      text = '甲';
    }else if(angle >= 82.5 && angle < 97.5){
      text = '卯';
    }else if(angle >= 97.5 && angle < 112.5){
      text = '乙';
    }else if(angle >= 112.5 && angle < 127.5){
      text = '辰';
    }else if(angle >= 127.5 && angle < 142.5){
      text = '巽';
    }else if(angle >= 142.5 && angle < 157.5){
      text = '巳';
    }else if(angle >= 157.5 && angle < 172.5){
      text = '丙';
    }else if(angle >= 172.5 && angle < 187.5){
      text = '午';
    }else if(angle >= 187.5 && angle < 202.5){
      text = '丁';
    }else if(angle >= 202.5 && angle < 217.5){
      text = '未';
    }else if(angle >= 217.5 && angle < 232.5){
      text = '坤';
    }else if(angle >= 232.5 && angle < 247.5){
      text = '申';
    }else if(angle >= 247.5 && angle < 262.5){
      text = '庚';
    }else if(angle >= 262.5 && angle < 277.5){
      text = '酉';
    }else if(angle >= 277.5 && angle < 292.5){
      text = '辛';
    }else if(angle >= 292.5 && angle < 307.5){
      text = '戌';
    }else if(angle >= 307.5 && angle < 322.5){
      text = '乾';
    }else if(angle >= 322.5 && angle < 337.5){
      text = '亥';
    }else if(angle >= 337.5 && angle < 352.5){
      text = '壬';
    }
    var textStr = 'markers[1].callout.content';
    this.setData({
      [textStr]:text
    })
  },
  //存入缓存
  setStoryage(content){
    var list = wx.getStorageSync('history')
    if (list) {
      var listArr = JSON.parse(list)
      listArr.forEach((item,index)=>{
        if(item == content){
          listArr.splice(index,1)
        }
      })
      listArr.unshift(content);
      var listStr = JSON.stringify(listArr)
      wx.setStorageSync('history', listStr)
      this.setData({
        historyList:listArr
      })
    }else{
      var arr = [];
      arr.unshift(content);
      var arrStr = JSON.stringify(arr)
      wx.setStorageSync('history', arrStr)
      this.setData({
        historyList:arr
      })
    }
  },
  //取出缓存
  getStorage(){
    var This = this;
    wx.getStorage({
      key: 'history',
      success (res) {
        var list = JSON.parse(res.data)
        This.setData({
          historyList:list
        })
      }
    })
  },
  //点击历史记录项
  clickHistoryItem(e){
    var address = e.target.dataset.address.split(":")[1];
    var This = this;
    var qqmapsdk = new QQMapWX({
      key: 'DTYBZ-MNUCV-HQOP3-UD5FF-BLBQT-ATFI2' // 必填
    })
    qqmapsdk.geocoder({
      address,
      success: function (res) {
        let longitude = res.result.location.lng;
        let latitude = res.result.location.lat;
        wx.showModal({
          title: '提示',
          content: '应用在起点还是终点',
          cancelText: '起点',
          confirmText: '终点',
          success (res1) {
            if (res1.confirm) {
              This.setData({
                [markersLng2]: longitude,
                [markersLat2]: latitude,
                [pointsLng2]: longitude,
                [pointsLat2]: latitude,
                [includeLng2]: longitude,
                [includeLat2]: latitude,
                endAddress:  address, //终点地址
              })
              var SLng = This.data.markers[0].longitude;
              var SLat = This.data.markers[0].latitude;
              This.calculateShichen(SLng, SLat, latitude, latitude);
              This.getDistance();
            } else if (res1.cancel) {
              This.setData({
                [markersLng1]: longitude,
                [markersLat1]: latitude,
                [pointsLng1]: longitude,
                [pointsLat1]: latitude,
                [startAdress]: address,
                [includeLng1]: longitude,
                [includeLat1]: latitude,
              })
              var ELng = This.data.markers[1].longitude;
              var ELat = This.data.markers[1].latitude;
              This.calculateShichen(longitude, latitude, ELng, ELat);
              This.getDistance();
            }
          }
        })
      },
      fail: function (res) {
        console.log(res);
      },
    })
  },
  //阻止冒泡
  catch(){},
  //点击选择地图类型按钮
  mapType() {
    this.setData({
      maskFlag:true,
      maskContent:true
    })
  },
  //点击选择历史按钮
  history() {
    this.setData({
      maskFlag:true,
      maskContent:false
    })
  },
  //hide遮罩层
  hideMask() {
    this.setData({
      maskFlag:false
    })
  },
  //普通地图
  putong(){
    this.setData({
      scale: 12,
      enableSatellite: false,//是否显示卫星图
      enable3D: false,//是否显示3D地图
    })
  },
  //卫星地图
  weixing(){
    this.setData({
      scale: 12,
      enableSatellite: true,//是否显示卫星图
      enable3D: false,//是否显示3D地图
    })
  },
  //3D地图
  sanDitu(){
    this.setData({
      scale: 20,
      enableSatellite: false,//是否显示卫星图
      enable3D: true,//是否显示3D地图
    })
  },
  regionchange(){}
})